package com.hollowlatte.manage.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hollowlatte.common.utils.Result;
import com.hollowlatte.manage.entity.Perms;
import com.hollowlatte.manage.entity.vo.PermsVO;
import com.hollowlatte.manage.service.PermsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hollow Latte
 * @since 2021-04-27
 */
@RequiresRoles("admin")
@Tag(name = "PermsController", description = "权限控制器")
@CrossOrigin
@RestController
@RequestMapping("/perms")
public class PermsController {
    @Autowired
    private PermsService permsService;

    @Operation(summary = "添加权限", description = "传入name即可")
    @PostMapping("")
    public Result addPerms(@RequestBody PermsVO permsVO) {
        Perms perms = new Perms();
        perms.setName(permsVO.getName());

        boolean affect = permsService.save(perms);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "删除权限")
    @DeleteMapping()
    public Result deletePerms(@RequestParam Long permsId) {
        boolean affect = permsService.removeById(permsId);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "修改权限", description = "根据id修改")
    @PutMapping("")
    public Result modifyPermsById(@RequestBody PermsVO permsVO) {
        Perms perms = new Perms();
        BeanUtils.copyProperties(permsVO, perms);

        boolean affect = permsService.updateById(perms);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "分页查询")
    @GetMapping("pagination")
    public Result paging(@RequestParam Long current, @RequestParam Long size) {
        Page<Perms> permsPage = new Page<>(current, size);
        permsService.page(permsPage);

        Page<PermsVO> permsVOPage = new Page<>();
        BeanUtils.copyProperties(permsPage, permsVOPage);

        permsVOPage.setRecords(permsPage.getRecords()
                .stream()
                .map(perms -> {
                    PermsVO permsVO = new PermsVO();
                    BeanUtils.copyProperties(perms, permsVO);
                    return permsVO;
                })
                .collect(Collectors.toList())
        );

        return Result.ok().data("pageInfo", permsVOPage);
    }
}

